package com.cloudwave.trailends.ui;

import java.io.UnsupportedEncodingException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cloudwave.trailends.AppContext;
import com.cloudwave.trailends.Constants;
import com.cloudwave.trailends.R;
import com.cloudwave.trailends.domain.User;
import com.cloudwave.trailends.entity.ResultEntity;
import com.cloudwave.trailends.utils.RegexUtils;
import com.cloudwave.trailends.utils.StatisticsUtils;
import com.cloudwave.trailends.widget.dialog.ColaProgress;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * @description 用户注册
 * @author DolphinBoy
 * 
 */
public class SignupActivity extends Activity {
	private static final String TAG = "SignupActivity";
	
	private ImageButton btnBack;
//	private ImageButton btnOK;
	private TextView tvTitle;
	
	private EditText etAccount;
	private EditText etPasswrod;
	
	private TextView tvSignup;
	private TextView tvSignin;
	
	private ColaProgress cp = null;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);
		
        iniView();
    }
	
	
	private void iniView() {
		btnBack = (ImageButton) findViewById(R.id.btnBack);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
//		btnOK = (ImageButton) findViewById(R.id.btnOK);
		
		etAccount = (EditText) findViewById(R.id.etAccount);
		etPasswrod = (EditText) findViewById(R.id.etPasswrod);
		
		tvSignup = (TextView) findViewById(R.id.tvSignup);
		tvSignin = (TextView) findViewById(R.id.tvSignin);
		
		tvTitle.setText(R.string.signup_title);
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SignupActivity.this.finish();
			}
		});
		tvSignin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SignupActivity.this, SigninActivity.class);
				startActivity(intent);
				SignupActivity.this.finish();
			}
		});
		tvSignup.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dealSignup();
			}
		});
	}
	
	private void dealSignup() {
//		resetSigninBtn(1);
		cp = ColaProgress.show(SignupActivity.this, "", true, false, null);
		
		String username = this.etAccount.getText().toString();
		String password = this.etPasswrod.getText().toString();
		
		if (TextUtils.isEmpty(username)) {
			Toast.makeText(SignupActivity.this, "账号不能为空!", Toast.LENGTH_SHORT).show();
//			resetSigninBtn(2);
			return ;
		}
		
		int len = 0;
		try {
			len = username.getBytes("utf-8").length;
		} catch (UnsupportedEncodingException e1) {
			len = 0;
		}
		
		String str = RegexUtils.filterAll(username);
		if ( TextUtils.isEmpty(str) ) {
			Toast.makeText(SignupActivity.this, "存在非法字符，只允许中文、字母、数字!", Toast.LENGTH_SHORT).show();
//			resetSigninBtn(2);
			return ;
		} else {
			int lenTmp = 0;
			try {
				lenTmp = str.getBytes("utf-8").length;
			} catch (UnsupportedEncodingException e1) {
				lenTmp = 0;
			}
			if ( len > lenTmp ) {
				Toast.makeText(SignupActivity.this, "存在非法字符，只允许中文、字母、数字!", Toast.LENGTH_SHORT).show();
//				resetSigninBtn(2);
				return ;
			}
		}
		
		if (len < 6 || len > 25) {
			Toast.makeText(SignupActivity.this, "账号必须大于5个字符并且小于25个字符!", Toast.LENGTH_SHORT).show();
//			resetSigninBtn(2);
			return ;
		}
		
		if (TextUtils.isEmpty(password)) {
			Toast.makeText(SignupActivity.this, "密码不能为空!", Toast.LENGTH_SHORT).show();
//			resetSigninBtn(2);
			return ;
		}
		
		int lenpwd = password.length();
		String pwd = RegexUtils.filtUnNcu(password);
		
		if ( pwd.length() < lenpwd ) {
			Toast.makeText(SignupActivity.this, "存在非法字符，只允许应为数字下划线!", Toast.LENGTH_SHORT).show();
//			resetSigninBtn(2);
			return ;
		}
		
		if (password.length() < 6 || password.length() > 16) {
			Toast.makeText(SignupActivity.this, "密码必须大于5个字符并且小于16个字符!", Toast.LENGTH_SHORT).show();
//			resetSigninBtn(2);
			return ;
		}
		
		cp.show();
		
		RequestParams params = new RequestParams();
//		params.addHeader("api-version", "1");
//		String cid = ((AppContext) getApplication()).getAppMeta("UMENG_CHANNEL");
//		params.addBodyParameter("cid", cid);
		StatisticsUtils.newInstance(this).appendParams("1", params);
		
		params.addBodyParameter("username", username);
		params.addBodyParameter("password", password);
		params.addBodyParameter("needuser", "true");
//		params.addQueryStringParameter("account", account);
//		params.addQueryStringParameter("password", passwrod);
//		params.addQueryStringParameter("needuser", "true");
		
		
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.POST, Constants.URL_SINGUP, params, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				
				if (responseInfo.statusCode != 200 && TextUtils.isEmpty(responseInfo.result)) {
					Toast.makeText(SignupActivity.this, "未获取到返回数据,请重试!", Toast.LENGTH_SHORT).show();
//					resetSigninBtn(2);
					cp.dismiss();
					Log.i(TAG, "未获取到返回数据!");
				} else {
					Log.i(TAG, "获取到返回数据:"+responseInfo.result);
//					String jsonStr = responseInfo.result.replaceAll("\\\\", "");
					ResultEntity rt = JSON.parseObject(responseInfo.result, ResultEntity.class);
					if ( !rt.isSuccess() ) {
						Toast.makeText(SignupActivity.this, rt.getCodeMsg(), Toast.LENGTH_SHORT).show();
						return ;
					} else {
						try {
//							UserInfo userInfo = JSON.parseObject(rt.data.toString(), UserInfo.class);
//							User user = userInfo.getUser();
							User user = JSON.parseObject(rt.data.toString(), User.class);
							user.isSessionUser(true);
							
							((AppContext) getApplication()).cacheLoginUser(user);
							
//							userInfo.setUser(null);
//							((AppContext) getApplication()).cacheLoginUserInfo(userInfo);
							
							// 写入到数据库
							DbUtils dbu = DbUtils.create(SignupActivity.this, Constants.DB_NAME);
							dbu.saveOrUpdate(user);
							
							Toast.makeText(SignupActivity.this, "注册成功!", Toast.LENGTH_SHORT).show();
							showMain();
						} catch (Exception e) {
							Toast.makeText(SignupActivity.this, "保存数据异常,请重试!", Toast.LENGTH_SHORT).show();
//							resetSigninBtn(2);
							cp.dismiss();
							Log.e(TAG, "异常信息:"+e.getMessage());
						}
					}
				}
			}
			
			@Override
			public void onFailure(HttpException error, String msg) {
//				if (error.getExceptionCode() == 403) {
//					Toast.makeText(SignupActivity.this, "对不起,您无权访问!", Toast.LENGTH_SHORT).show();
//				} else if (error.getExceptionCode() == 404) {
//					Toast.makeText(SignupActivity.this, "对不起,访问地址错误!", Toast.LENGTH_SHORT).show();
//				} else {
//					Toast.makeText(SignupActivity.this, "注册失败,请检查您的网络!", Toast.LENGTH_SHORT).show();
//				}
				Toast.makeText(SignupActivity.this, "注册失败,请检查您的网络!", Toast.LENGTH_SHORT).show();
//				resetSigninBtn(2);
				cp.dismiss();
				Log.i(TAG, "error code:"+error.getExceptionCode());
				Log.i(TAG, "msg:"+msg);
				Log.e(TAG, error.getMessage());
			}
		});
		
	}
	
	private void showMain() {
		Intent intent = new Intent(SignupActivity.this, MainActivity.class);
		startActivity(intent);
		this.finish();
	}
	
//	private void resetSigninBtn(int code) {
//		etAccount.clearFocus();
//		etPasswrod.clearFocus();
//		
//		if (code == 1) {
//			tvSignup.setOnClickListener(null);
//			tvSignup.setBackgroundResource(R.color.them_gray);
//		} else if (code == 2) {
//			tvSignup.setBackgroundResource(R.color.white);
//			tvSignup.setOnClickListener(new View.OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					dealSignup();
//				}
//			});
//			tvSignin.setBackgroundResource(R.color.white);
//		}
//	}
}
